<template>
  <vxe-modal :loading="loadings" :title="titles" v-model="addxmls" width="95%" showFooter show-zoom resize
             height="96vh">
    <!-- 顶部搜索 -->
    <el-form :model="queryParams" ref="queryForm" size="small" v-show="showSearch" label-width="68px">
      <el-row :gutter="24">
        <el-col :span="6">
          <el-form-item label="科目" prop="km">
            <el-input
              v-model="queryParams.km"
              placeholder="请输入科目"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="锁定状态" prop="sdZt">
            <el-select v-model="queryParams.sdZt" placeholder="请选择锁定状态" clearable>
              <el-option
                v-for="dict in dict.type.sdzt"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="凭证日期">
            <el-date-picker
              v-model="daterangePzTime"
              style="width: 100%"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 顶部按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-edit"
          size="mini"
          @click="handleUpdate"
          :disabled="!selectedRow || (selectedRow.sdZt !== '未锁')"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-delete"
          size="mini"
          @click="handleDelete"
          :disabled="!selectedRow || (selectedRow.sdZt !== '未锁')"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="vxe-icon-unlock"
          size="mini"
          @click="handleSd"
          :disabled="!selectedRow || (selectedRow.sdZt !== '未锁')"
        >锁定
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="vxe-icon-unlock-fill"
          size="mini"
          @click="handleJs"
          :disabled="!selectedRow || (selectedRow.sdZt !== '锁定')"
        >解锁
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格 -->
    <el-table @row-click="clickRow" ref="table" highlight-current-row :row-class-name="tableRowClassName"
              :stripe="false" height="300"
              :header-cell-style="{background:'#d0cece',color:'#000000',fontWeight:'bold'}"
              class="fixedTableOne" v-loading="loading" :data="xmlsList" @selection-change="handleSelectionChange">
      <!--      <el-table-column type="selection" width="55" align="center"/>-->
      <el-table-column label="序号" align="center" type="index" :index="indexMethod"/>
      <el-table-column label="科目序号" align="center" prop="kmXh"/>
      <el-table-column show-overflow-tooltip label="科目" align="center" prop="km" width="300"/>
      <el-table-column show-overflow-tooltip label="研发活动证明(材料消耗)" align="center" prop="clXh">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="handleButtonClXhClick(scope.row)"
          >
            <el-link type="primary">{{ scope.row.clXh }}</el-link>
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="凭证日期" align="center" prop="pzTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.pzTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip label="凭证号" align="center" prop="pzh"/>
      <el-table-column label="凭证种类" align="center" prop="pzZl">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="handleButtonClick(scope.row)"
          >
            <el-link type="primary">{{ scope.row.pzZl }}</el-link>
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="借/贷" align="center" prop="jd">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.lstb_xmls_jd" :value="scope.row.jd"/>
        </template>
      </el-table-column>
      <el-table-column label="金额" align="center" prop="je"/>
      <el-table-column label="摘要" align="center" prop="zy"/>
      <el-table-column label="锁定状态" align="center" prop="sdZt" width="80">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sdzt" :value="scope.row.sdZt"/>
        </template>
      </el-table-column>
      <el-table-column label="锁定(解锁)日期" align="center" prop="sTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.sTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="锁定(解锁)人" align="center" prop="sName"/>
      <el-table-column label="申请人" align="center" prop="createBy"/>
      <el-table-column label="申请时间" align="center" prop="createTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="申请单位" align="center" prop="deptName"/>
      <!--      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">-->
      <!--        <template slot-scope="scope">-->
      <!--          <el-button-->
      <!--            size="mini"-->
      <!--            type="text"-->
      <!--            icon="el-icon-edit"-->
      <!--            @click="handleUpdate(scope.row)"-->
      <!--          >修改-->
      <!--          </el-button>-->
      <!--          <el-button-->
      <!--            size="mini"-->
      <!--            type="text"-->
      <!--            icon="el-icon-delete"-->
      <!--            @click="handleDelete(scope.row)"-->
      <!--          >删除-->
      <!--          </el-button>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改项目流水对话框 -->
    <vxe-modal :title="title" v-model="open" width="70%" showFooter show-zoom resize>
      <el-form ref="formDialog" :model="form" :rules="rules" label-width="175px">
        <div style="height: 70vh;">
          <!-- 基本信息 -->
          <el-card class="box-card">
            <div slot="header" class="clearfix" style="text-align: center;">
              <span style="font-size: 20px; color: #1890ff">基本信息</span>
            </div>
            <el-form-item v-if="1 === 2" label="项目申报ID" prop="xmsbId">
              <el-input v-model="form.xmsbId" placeholder="请输入项目申报ID"/>
            </el-form-item>
            <el-form-item v-if="1 === 2" label="流水填报ID" prop="lstbId">
              <el-input v-model="form.lstbId" placeholder="请输入流水填报ID"/>
            </el-form-item>
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item label="项目名称" prop="xmName">
                  <el-input disabled v-model="form.xmName" placeholder="请输入项目名称"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="项目类型" prop="xmLx">
                  <el-input disabled v-model="form.xmLx" placeholder="请输入项目类型"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item label="科目" prop="km">
                  <!--                  <el-input v-model="form.km" placeholder="请输入科目"/>-->
                  <el-cascader @change="addKmXh()" v-model="form.km" :options="kmOptions" :show-all-levels="false"
                               style="width: 100%;"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="凭证日期" prop="pzTime">
                  <el-date-picker clearable style="width: 100%;"
                                  v-model="form.pzTime"
                                  type="date"
                                  value-format="yyyy-MM-dd"
                                  placeholder="请选择凭证日期">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item :rules="[{ required: true, message: '请关联研发活动证明(材料消耗)', trigger: 'blur' }]"
                          v-if="form.kmXh == '2.1'" label="研发活动证明(材料消耗)" prop="clXh" @focus="selectClXh">
              <el-input v-model="form.clXh" placeholder="请关联研发活动证明(材料消耗)" @focus="selectClXh()"
                        :suffix-icon="'el-icon-search'">
              </el-input>
            </el-form-item>
            <el-form-item v-if="1 === 2" label="材料消耗填报ID" prop="clxhtbId">
              <el-input v-model="form.clxhtbId" placeholder="请输入材料消耗填报ID"/>
            </el-form-item>
            <el-form-item v-if="1 === 2" label="科目序号" prop="kmXh">
              <el-input v-model="form.kmXh" placeholder="请输入科目序号"/>
            </el-form-item>
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item label="凭证种类" prop="pzZl">
                  <el-select v-model="form.pzZl" placeholder="请选择凭证种类">
                    <el-option
                      v-for="dict in dict.type.lstb_xmls_pzzl"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="凭证号" prop="pzh">
                  <el-input v-model="form.pzh" placeholder="请输入凭证号"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item label="借/贷" prop="jd">
                  <el-select v-model="form.jd" placeholder="请选择借/贷">
                    <el-option
                      v-for="dict in dict.type.lstb_xmls_jd"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="金额" prop="je">
                  <el-input-number style="width: 100%;" v-model="form.je" placeholder="请输入金额"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="摘要" prop="zy">
              <el-input v-model="form.zy" type="textarea" placeholder="请输入内容"/>
            </el-form-item>
          </el-card>
          <br>
          <!-- 附件资料 -->
          <el-card class="box-card">
            <div slot="header" class="clearfix" style="text-align: center;">
              <span style="font-size: 20px; color: #1890ff">附件资料</span>
            </div>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <!-- 上传按钮 -->
                <el-button size="mini" icon="el-icon-upload" type="primary" @click="xmlsFileUpload">上传</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteLstbXmlsFj">删除
                </el-button>
              </el-col>
            </el-row>
            <el-table :header-cell-style="{background:'#d0cece',color:'#000000',fontWeight:'bold'}"
                      :data="lstbXmlsFjList" :row-class-name="rowLstbXmlsFjIndex" height="30vh"
                      @selection-change="handleLstbXmlsFjSelectionChange" ref="lstbXmlsFj">
              <el-table-column type="selection" width="50" align="center"/>
              <el-table-column label="序号" align="center" prop="index" width="50"/>
              <el-table-column show-overflow-tooltip label="文件名称" align="center" prop="fileName"
                               :formatter="getFileNames"/>
              <el-table-column label="文件大小" align="center" prop="fileSize"/>
              <el-table-column label="操作" width="120" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-view"
                    @click="handlePreview(scope.row)"
                  >预览
                  </el-button>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-edit"
                    @click="handleDownload(scope.row)"
                  >下载
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </vxe-modal>

    <!-- 项目流水附件上传弹窗 -->
    <vxe-modal title="附件上传" v-model="fjUpload" width="25%" showFooter show-zoom resize @close="fjClose">
      <el-upload
        align="center"
        class="upload-demo"
        multiple
        :action="uploadFileUrl"
        :before-upload="handleBeforeUpload"
        :file-list="fileList"
        :limit="20"
        :on-error="handleUploadError"
        :on-exceed="handleExceed"
        :on-success="handleUploadSuccess"
        :headers="headers"
        ref="fileUpload"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">
          请上传
          <template> 大小不超过 <b style="color: #f56c6c">{{ 50 }}MB</b></template>
          <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b></template>
          的文件
        </div>
      </el-upload>

      <div slot="footer" class="dialog-footer" style="display: flex; justify-content: center;">
        <el-button v-if="allFilesUploaded === false" size="mini" type="primary" @click="fjUpload = false">关 闭
        </el-button>
        <el-button v-if="allFilesUploaded === true" size="mini" type="primary" @click="fjClose">上传完成, 关闭
        </el-button>
      </div>

    </vxe-modal>

    <!-- 预览组件 -->
    <KkFileView ref="preview"/>

    <!-- 项目流水详情 -->
    <XmLsXq ref="xmLsXq"/>

    <!-- 材料消耗单选 -->
    <ClXhDx ref="clXgDx"/>

    <!-- 材料消耗填报详情 -->
    <ClXhTbXq ref="clXhTbXq"/>

  </vxe-modal>
</template>

<script>
import {
  addXmls,
  deleteLstbXmlsFjByFjIds,
  delXmls,
  getXmls,
  getXmLsId,
  insertXmlsFjByXmlsId,
  listXmls,
  selectXmlsFjList,
  updateXmls
} from "@/api/fztz/xmls";
import {listFykm} from "@/api/fztz/fykm";
import {getToken} from "@/utils/auth";
import KkFileView from "@/views/components/KKFileView/kkFileView.vue";
import XmLsXq from "@/views/fztz/xmls/components/XmLsXq.vue";
import ClXhDx from "@/views/components/ClXhDx/ClXhDx.vue";
import ClXhTbXq from "@/views/fztz/clxhtb/components/ClXhTbXq.vue";

export default {
  name: "Xmls",
  components: {ClXhTbXq, ClXhDx, XmLsXq, KkFileView},
  dicts: ['lstb_xmls_pzzl', 'lstb_xmls_jd', 'sdzt'],
  provide() {
    return {
      updateClXhLabel: (val) => {
        this.form.clxhtbId = val.clxhtbId
        this.form.clXh = '(第' + val.jlCs + '次)' + val.xmName
        this.$refs['formDialog'].validateField('clXh');
      },
    };
  },
  data() {
    return {
      km: null, //点击修改时查询出的科目
      xg: false, //判断是新增还是修改 (false新增 true修改)
      allFilesUploaded: false, // 添加这个来追踪所有文件是否上传完成
      fjUpload: false, //附件上传弹窗
      //要修改的 项目流水id
      xmlsIdEdit: "",
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传文件服务器地址
      fileList: [],
      headers: {Authorization: "Bearer " + getToken()},
      number: 0,
      uploadList: [],
      fileType: ["doc", "xls", "ppt", "txt", "pdf", "docx", "zip"],
      loadings: false,
      getXmLsId: null, //从后端获取到的项目流水ID
      rowData: [], //从流水填报页面传过来的值
      addxmls: false, //控制整个弹窗开关
      selectedRow: null, // 保存当前选中的行
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedLstbXmlsFj: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 项目流水表格数据
      xmlsList: [],
      // 项目流水附件表格数据
      lstbXmlsFjList: [],
      // 弹出层标题
      title: "",
      titles: "",
      // 是否显示弹出层
      open: false,
      // 文件大小时间范围
      daterangePzTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        lstbId: null,
        km: null,
        pzTime: null,
        idWhere: null,
        userId: null,
        deptId: null,
        sdZt: null,
        xmsbId: null,
        clxhtbId: null,
        clXh: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        lstbId: [{required: true, message: "流水填报ID不能为空", trigger: "blur"}],
        xmName: [{required: true, message: "项目名称不能为空", trigger: "blur"}],
        xmLx: [{required: true, message: "项目类型不能为空", trigger: "blur"}],
        km: [{required: true, message: "科目不能为空", trigger: "blur"}],
        pzTime: [{required: true, message: "凭证日期不能为空", trigger: "blur"}],
        pzh: [{required: true, message: "凭证号不能为空", trigger: "blur"}],
        jd: [{required: true, message: "借/贷不能为空", trigger: "change"}],
        je: [{required: true, message: "金额不能为空", trigger: "blur"}],
      },
      kmOptions: null, //查询到的所有科目
    };
  },
  created() {
    this.getKmList();
  },
  methods: {
    handleButtonClXhClick(row) {
      this.$refs.clXhTbXq.handleOpen(row)
    },
    // 打开选择材料消耗单选组件
    selectClXh() {
      this.$refs.clXgDx.handleOpen(this.form.xmsbId)
    },
    //打开项目流水详情组件
    handleButtonClick(row) {
      this.$refs.xmLsXq.handleOpen(row)
    },
    //行内锁定状态为锁定时, 将该行背景颜色改为灰色
    tableRowClassName: function ({row, rowIndex}) {
      if (row.sdZt === '锁定') {
        return 'warm-row';
      }
    },
    //解锁
    handleJs() {
      const row = this.selectedRow; //将当前行的数据赋值给row
      this.$confirm('确定解锁选中记录？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 打开遮罩层
        this.$modal.loading("正在解锁中，请稍后...");
        let xmlsFrom = {
          xmlsId: row.xmlsId,
          sdZt: '未锁',
          sTime: this.getCurrentDate(),
          sName: this.$store.state.user.name
        }
        updateXmls(xmlsFrom).then(response => {
          this.getList();
          this.$message({
            type: 'success',
            message: '解锁成功!'
          });
          // 关闭遮罩层
          this.$modal.closeLoading();
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消解锁'
        });
      });
    },
    //锁定
    handleSd() {
      const row = this.selectedRow; //将当前行的数据赋值给row
      this.$confirm('确定锁定选中记录？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 打开遮罩层
        this.$modal.loading("正在锁定中，请稍后...");
        let xmlsFrom = {
          xmlsId: row.xmlsId,
          sdZt: '锁定',
          sTime: this.getCurrentDate(),
          sName: this.$store.state.user.name
        }
        updateXmls(xmlsFrom).then(response => {
          this.getList();
          this.$message({
            type: 'success',
            message: '锁定成功!'
          });
          // 关闭遮罩层
          this.$modal.closeLoading();
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消锁定'
        });
      });
    },
    // 打开预览组件
    handlePreview(row) {
      this.$refs.preview.handleOpen(row);
    },
    // 文件下载处理
    handleDownload(row) {
      const resource = row.fileName;
      // 默认方法
      this.$download.resource(resource);
    },
    // 获取文件名原名
    getFileNames(row) {
      // 从路径中提取文件名
      return row.fileName.split('/').pop(); // 返回文件名部分
    },
    //关闭上传附件弹窗后
    fjClose() {
      this.fileList = []
      this.allFilesUploaded = false
      this.fjUpload = false
    },
    //上传文件之前的钩子
    handleBeforeUpload(file) {
      let that = this;
      // 校检文件类型
      if (this.fileType) {
        const fileName = file.name.split('.');
        const fileExt = fileName[fileName.length - 1];
        const isTypeOk = this.fileType.indexOf(fileExt) >= 0;
        if (!isTypeOk) {
          this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`);
          return false;
        }
        // 校检文件大小
        if (this.fileSize) {
          const isLt = file.size / 1024 / 1024 < this.fileSize;
          if (!isLt) {
            this.$modal.msgError(`上传文件大小不能超过 ${this.fileSize} MB!`);
            return false;
          }
        }
        this.$modal.loading("正在上传文件，请稍候...");
        this.number++;
        return true;
      }
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let strs = "";
      separator = separator || ",";
      for (let i in list) {
        strs += list[i].url + separator;
      }
      return strs !== '' ? strs.substr(0, strs.length - 1) : '';
    },
    // 上传失败
    handleUploadError() {
      this.$modal.msgError("上传文件失败，请重试");
      this.$modal.closeLoading();
    },
    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传成功
    handleUploadSuccess(res, file) {
      let that = this;
      if (res.code === 200) {
        this.uploadList.push({name: res.fileName, url: res.fileName, size: that.formatFileSize(file.size)});
        let xzItemFile = {
          "xmlsId": that.getXmLsId,
          "fileName": res.fileName,
          "fileSize": that.formatFileSize(file.size)
        };
        let xgItemFile = {
          "xmlsId": that.xmlsIdEdit,
          "fileName": res.fileName,
          "fileSize": that.formatFileSize(file.size)
        };
        if (this.xg === false) {
          // 点击新增按钮的上传
          insertXmlsFjByXmlsId(xzItemFile).then(resFil => {
            that.getXmLsFjList();
          })
        } else if (this.xg === true) {
          // 点击修改按钮的上传
          insertXmlsFjByXmlsId(xgItemFile).then(resFil => {
            that.getXmLsFjList();
          })
        }
        this.uploadedSuccessfully();
      } else {
        this.number--;
        this.$modal.closeLoading();
        this.$modal.msgError(res.msg);
        this.$refs.fileUpload.handleRemove(file);
        this.uploadedSuccessfully();
      }
      this.allFilesUploaded = true
      this.$modal.msgSuccess("上传成功")
      // this.fjShangChuan = false
    },
    getXmLsFjList() {
      let that = this;
      if (this.xg === false) {
        //点击新增 上传文件后的文件列表
        selectXmlsFjList(that.getXmLsId).then(resFileList => {
          that.lstbXmlsFjList = resFileList.data;
        })
      } else {
        //点击修改 上传文件后的文件列表
        selectXmlsFjList(that.xmlsIdEdit).then(resFileList => {
          that.lstbXmlsFjList = resFileList.data;
        })
      }
    },
    // 显示文件大小为KB, MB, GB, TB
    formatFileSize(size) {
      if (size === 0) return '0 Bytes';
      const k = 1024;
      const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
      const i = Math.floor(Math.log(size) / Math.log(k));
      return parseFloat((size / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    },
    // 获取文件名称
    getFileName(name) {
      // 如果是url那么取最后的名字 如果不是直接返回
      if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1);
      } else {
        return name;
      }
    },
    // 上传结束处理
    uploadedSuccessfully() {
      if (this.number > 0 && this.uploadList.length === this.number) {
        this.fileList = this.fileList.concat(this.uploadList);
        this.fileList = this.fileList.map(item => {
          // 使用split方法去除name中的特定前缀
          item.name = item.name.split('/').pop();
          return item;
        });
        this.uploadList = [];
        this.number = 0;
        this.$emit("input", this.listToString(this.fileList));
        this.$modal.closeLoading();
      }
    },
    //项目流水附件上传按钮
    xmlsFileUpload() {
      this.fjUpload = true;
    },
    getKmList() {
      listFykm().then(res => {
        this.kmOptions = this.transformData(res.data)
      })
    },
    //将数据转换成级联选择器需要的格式
    transformData(data) {
      const map = {};
      const result = [];

      // 创建映射表
      data.forEach(item => {
        map[item.fykmId] = {value: item.kmName, label: item.kmName, xh: item.xh, children: []};
      });

      // 建立父子关系
      data.forEach(item => {
        const node = map[item.fykmId];
        if (item.fId === 0) { // 顶级节点
          result.push(node);
        } else {
          if (map[item.fId]) { // 确保父节点存在
            if (!map[item.fId].children) {
              map[item.fId].children = [];
            }
            map[item.fId].children.push(node);
          } else {
            console.warn(`Parent node with fId ${item.fId} not found for node ${item.fykmId}`);
          }
        }
      });

      // 过滤掉没有子节点的节点
      function filterEmptyChildren(nodes) {
        nodes.forEach(node => {
          if (node.children.length === 0) {
            delete node.children; // 移除空的 children 属性
          } else {
            filterEmptyChildren(node.children); // 递归处理子节点
          }
        });
      }

      filterEmptyChildren(result);

      return result;
    },
    addKmXh() {
      const selectedOption = this.findOptionByValue(this.kmOptions, this.form.km);
      if (selectedOption && selectedOption.xh) {
        this.form.kmXh = selectedOption.xh
      }
    },
    findOptionByValue(options, value) {
      for (let option of options) {
        if (option.value === value[value.length - 1]) {
          return option;
        }
        if (option.children) {
          const found = this.findOptionByValue(option.children, value);
          if (found) return found;
        }
      }
      return null;
    },
    //打开整个弹窗
    handleOpen(row) {
      this.loadings = true
      this.rowData = row
      this.titles = '【' + row.xmName + '】' + '流水填报'
      this.addxmls = true
      this.getList()
    },
    //点击行 获取行
    clickRow(row) {
      this.selectedRow = row; // 更新选中的行
      const table = this.$refs.table;
      const selectedRows = table.selection;

      // 否则取消之前选中的行，并选中当前点击的行
      selectedRows.forEach(selectedRow => {
        table.toggleRowSelection(selectedRow);
      });
      table.toggleRowSelection(row);
    },
    /** 自定义序号 */
    indexMethod(index) {
      let pageNum = this.queryParams.pageNum - 1;
      if ((pageNum !== -1 && pageNum !== 0)) {
        return (index + 1) + (pageNum * this.queryParams.pageSize);
      } else {
        return (index + 1)
      }
    },
    /** 查询项目流水列表 */
    getList() {
      this.loading = true;
      this.queryParams.lstbId = this.rowData.lstbId
      this.queryParams.params = {};
      if (null != this.daterangePzTime && '' != this.daterangePzTime) {
        this.queryParams.params["beginPzTime"] = this.daterangePzTime[0];
        this.queryParams.params["endPzTime"] = this.daterangePzTime[1];
      }
      listXmls(this.queryParams).then(response => {
        this.xmlsList = response.rows;
        this.total = response.total;
        this.loading = false;
        this.loadings = false
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        xmlsId: this.getXmLsId,
        lstbId: this.rowData.lstbId,
        xmName: this.rowData.xmName,
        xmLx: this.rowData.xmLx,
        km: null,
        pzTime: null,
        pzZl: '记账凭证',
        pzh: null,
        jd: '借',
        je: null,
        zy: null,
        idWhere: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        userId: null,
        deptId: null,
        kmXh: null,
        sdZt: null,
        sTime: null,
        sName: null,
        xmsbId: this.rowData.xmsbId,
        clxhtbId: null,
        clXh: null,
      };
      this.lstbXmlsFjList = [];
      this.resetForm("formDialog");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangePzTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      let ids = selection.map(item => item.xmlsId)
      if (ids.length === 1) {
        this.ids = ids[0]
      } else {
        this.ids = ids
      }
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.xg = false
      getXmLsId().then(res => {
        this.getXmLsId = res.msg
        this.reset();
      })
      this.open = true;
      this.title = "添加项目流水";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      // this.reset();
      this.xg = true
      const xmlsId = row.xmlsId || this.ids
      this.xmlsIdEdit = row.xmlsId || this.ids
      getXmls(xmlsId).then(response => {
        this.form = response.data;
        this.km = response.data.km
        this.lstbXmlsFjList = response.data.lstbXmlsFjList;
        this.open = true;
        this.title = "修改项目流水";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["formDialog"].validate(valid => {
        if (valid) {
          this.form.lstbXmlsFjList = this.lstbXmlsFjList;
          if (this.form.idWhere != null) {
            if (this.form.km != this.km) {
              this.form.km = this.form.km[1]
            } else {
              this.form.km = this.km
            }
            updateXmls(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.xg = false
            });
          } else {
            this.form.km = this.form.km[1]
            addXmls(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const xmlsIds = row.xmlsId || this.ids;
      this.$modal.confirm('确定删除选中记录？').then(function () {
        return delXmls(xmlsIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 项目流水附件序号 */
    rowLstbXmlsFjIndex({row, rowIndex}) {
      row.index = rowIndex + 1;
    },
    /** 项目流水附件删除按钮操作 */
    handleDeleteLstbXmlsFj() {
      if (this.checkedLstbXmlsFj.length == 0) {
        this.$modal.msgError("请先选择要删除的项目流水附件数据");
      } else {
        const fjIds = this.checkedLstbXmlsFj;
        this.$modal.confirm('确定删除选中记录？').then(function () {
          return deleteLstbXmlsFjByFjIds(fjIds);
        }).then(() => {
          if (this.xg == false) {
            selectXmlsFjList(this.getXmLsId).then(resFileList => {
              this.lstbXmlsFjList = resFileList.data;
            })
          } else {
            getXmls(this.xmlsIdEdit).then(response => {
              this.lstbXmlsFjList = response.data.lstbXmlsFjList;
            });
          }
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
      }
    },
    /** 复选框选中数据 */
    handleLstbXmlsFjSelectionChange(selection) {
      this.checkedLstbXmlsFj = selection.map(item => item.fjId)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('fztz/xmls/export', {
        ...this.queryParams
      }, `xmls_${new Date().getTime()}.xlsx`)
    },
  }
};
</script>

<style lang="scss">
.warm-row {
  background-color: #eaeaea !important;
}
</style>
